﻿//<TunynetCopyright>
//--------------------------------------------------------------
//<copyright>青岛拓宇网络科技有限公司 2005-2008</copyright>
//<version>V0.5</verion>
//<createdate>2008-3-20</createdate>
//<author>mazq</author>
//<email>mazq@tunynet.com</email>
//<log date="2008-3-20">创建</log>
//--------------------------------------------------------------
//</TunynetCopyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChinaCustoms.Qingdao.Workflow.Supports;
using Tunynet.QingdaoCustoms.Utils;
using ChinaCustoms.Qingdao.Workflow.Permissions;

namespace ChinaCustoms.Qingdao.Workflow.Controls
{
    /// <summary>
    /// 工作流路径
    /// </summary>
    [ToolboxData("<{0}:WorkflowPath runat=server />")]
    public class WorkflowPath : TemplatedWebControl
    {
        protected override void OnInit(EventArgs e)
        {
            if (SkinName == null)
                ExternalSkinFileName = "Skin-WorkflowPath.ascx";
            else
                ExternalSkinFileName = SkinName;

            base.OnInit(e);
        }

        TreeView workflowTreeView;
        protected override void AttachChildControls()
        {
            workflowTreeView = FindControl("WorkflowTreeView") as TreeView;
        }


        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            EnsureChildControls();

            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(this.Context.Request.QueryString["WorkItemID"]))
                    this.workItemID = int.Parse(this.Context.Request.QueryString["WorkItemID"]);

                if (!string.IsNullOrEmpty(this.Context.Request.QueryString["TaskID"]))
                    this.taskID = int.Parse(this.Context.Request.QueryString["TaskID"]);

                if (WorkItemID <= 0 && TaskID <= 0)
                {
                    this.Visible = false;
                    return;
                }

                if (TaskID <= 0)
                {
                    WorkItemInfo currentWorkItem = WorkItems.GetWorkItem(this.WorkItemID);
                    if (currentWorkItem == null)
                    {
                        this.Visible = false;
                        return;
                    }
                    else
                    {
                        TaskID = currentWorkItem.TaskID;
                    }
                }

                TaskInfo task = Tasks.GetTask(TaskID);
                WorkflowInstanceInfo workflowInstanceInfo = WorkflowInstances.GetWorkflow(task.WorkflowGuid);

                string endActivityCodeName = string.Empty;
                if (workflowInstanceInfo.Status == WorkflowStatus.Runing)
                    endActivityCodeName = workflowInstanceInfo.ExecutingActivityCodeName;

                List<ActivityInstanceInfo> activites = ActivityInstances.GetActivities(task.WorkflowGuid);
                foreach (ActivityInstanceInfo activity in activites)
                {
                    if (activity.IsSubFlow)
                    {
                        int subFlowID = -1;
                        int parentSubFlowID = -1;

                        if (WorkItemID > 0)
                        {
                            WorkItemInfo currentWorkItem = WorkItems.GetWorkItem(this.WorkItemID);
                            subFlowID = currentWorkItem.SubFlowID;
                            if (subFlowID > 0)
                            {
                                SubFlowInfo currentSubFlow = SubFlows.GetSubFlow(subFlowID);
                                parentSubFlowID = currentSubFlow.ParentSubFlowID;
                            }
                        }

                        WorkItemInfo workItemOfActivity = WorkItems.GetWorkItem(activity.ActivityGuid, WorkItemStatus.Completed);
                        if (workItemOfActivity != null)
                        {
                            TreeNode subFlowActivityTreeNode = new TreeNode(activity.ActivityName);
                            subFlowActivityTreeNode.SelectAction = TreeNodeSelectAction.Expand;

                            workflowTreeView.Nodes.Add(subFlowActivityTreeNode);
                            List<SubFlowInfo> rootSubFlowsOfActivity = SubFlows.GetRootSubFlowsByActivityGuid(activity.ActivityGuid);
                            foreach (SubFlowInfo subFlow in rootSubFlowsOfActivity)
                            {
                                //非本子流程内的路径信息不允许查看
                                if ((parentSubFlowID > 0 && parentSubFlowID != subFlow.SubFlowID) && (subFlowID > 0 && subFlowID != subFlow.SubFlowID))
                                    continue;

                                TreeNode subFlowTreeNode = new TreeNode(string.Format("{0}（发起人：{1}，发起时间：{2}）", subFlow.SubFlowName, subFlow.SponsorUserName, subFlow.CreateDate.ToString()));
                                subFlowTreeNode.SelectAction = TreeNodeSelectAction.Expand;
                                subFlowActivityTreeNode.ChildNodes.Add(subFlowTreeNode);

                                List<WorkItemInfo> workItemsOfSubFlow = WorkItems.GetWorkItemsOfSubFlowPath(subFlow.SubFlowID);

                                foreach (WorkItemInfo workItem in workItemsOfSubFlow)
                                {
                                    subFlowTreeNode.ChildNodes.Add(PopulateTreeNodeFromWorkItem(workItem));
                                }

                                List<SubFlowInfo> childSubFlows = SubFlows.GetChildSubFlows(subFlow.SubFlowID);
                                foreach (SubFlowInfo childSubFlow in childSubFlows)
                                {
                                    //非本子流程内的路径信息不允许查看
                                    if (subFlowID > 0 && subFlowID != childSubFlow.SubFlowID && !PermissionUtils.StipIrrespectiveCharsForLogOnName(Context.User.Identity.Name).Equals(subFlow.SponsorUserName))
                                        continue;

                                    TreeNode childSubFlowTreeNode = new TreeNode(string.Format("{0}（发起人：{1}，发起时间：{2}）", childSubFlow.SubFlowName, childSubFlow.SponsorUserName, childSubFlow.CreateDate.ToString()));
                                    childSubFlowTreeNode.SelectAction = TreeNodeSelectAction.Expand;
                                    subFlowActivityTreeNode.ChildNodes.Add(childSubFlowTreeNode);

                                    List<WorkItemInfo> workItemsOfChildSubFlow = WorkItems.GetWorkItemsOfSubFlowPath(childSubFlow.SubFlowID);

                                    foreach (WorkItemInfo workItem in workItemsOfChildSubFlow)
                                    {
                                        childSubFlowTreeNode.ChildNodes.Add(PopulateTreeNodeFromWorkItem(workItem));
                                    }

                                    subFlowTreeNode.ChildNodes.Add(childSubFlowTreeNode);
                                }

                            }
                        }
                    }
                    else
                    {
                        WorkItemInfo workItemOfActivity = WorkItems.GetWorkItem(activity.ActivityGuid, WorkItemStatus.Completed);
                        if (workItemOfActivity != null)
                        {
                            workflowTreeView.Nodes.Add(PopulateTreeNodeFromWorkItem(workItemOfActivity));
                        }
                    }

                    if (activity.CodeName.Equals(endActivityCodeName, StringComparison.CurrentCultureIgnoreCase))
                        break;
                }

            }

        }

        /// <summary>
        /// 生成WorkItem 意见及附件节点
        /// </summary>
        /// <param name="workItem">工作项</param>
        TreeNode PopulateTreeNodeFromWorkItem(WorkItemInfo workItem)
        {
            TreeNode workItemTreeNode = null;
            if (workItem != null)
            {
                workItemTreeNode = new TreeNode();
                workItemTreeNode.SelectAction = TreeNodeSelectAction.Expand;

                workItemTreeNode.Text = workItem.WorkItemName + "（" + workItem.CreateDate.ToString() + "）";
                if (!string.IsNullOrEmpty(workItem.Postil.Trim()))
                {
                    workItemTreeNode.Text += "               意见：" + StringUtils.Trim(workItem.Postil, 100);
                }

                workItemTreeNode.Value = workItem.WorkItemID.ToString();
            }
            return workItemTreeNode;
        }


        #region 属性

        private int workItemID = -1;
        /// <summary>
        /// 工作项ID
        /// </summary>
        public int WorkItemID
        {
            get { return workItemID; }
            set { workItemID = value; }
        }

        private int taskID = -1;
        /// <summary>
        /// 任务ID
        /// </summary>
        public int TaskID
        {
            get { return taskID; }
            set { taskID = value; }
        }


        #endregion



    }
}
